<template>
  <div class="page">
    <nav-bar title="省心" :is-custom="true" @on-back="handleBack" @on-refresh="handleRefresh" />
    <home-card
      :amount="userData.gwj"
      :username="userName"
      :avatar="userData.avatar"
      @on-change-user="handleChangeUser"
      @on-record="handleRecord"
      @on-tips="handleTips"
    />
    <div class="mall">
      <div v-if="curTab === TabType.Goods" class="goods">
        <div class="goods-item" v-for="(goods, idx) in goodsData.list" :key="idx">
          <goods-card :goods="goods" @click="handleClickGoods(goods)" />
        </div>
        <empty-card
          v-if="goodsData.list.length === 0"
          :icon="''"
          :desc="'暂无商品'"
          :custom-style="'margin-top: 90px'"
        />
        <no-data v-if="goodsData.list.length && goodsData.loadAll" />
      </div>
      <div v-else-if="curTab === TabType.Order" class="order">
        <div class="order-item" v-for="(order, idx) in orderData.list" :key="idx">
          <order-card :order="order" @click="handleClickOrder" />
        </div>
        <empty-card v-if="orderData.list.length === 0" :custom-style="'margin-top: 90px'" />
        <no-data v-if="orderData.loadAll" />
      </div>
      <div ref="observerRef" class="observer"></div>
    </div>
    <tips-dialog ref="tipsDialogRef" />
  </div>
</template>
<script setup lang="ts">
import type { GoodsItem, OrderItem } from '@/types/mall'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import NavBar from '@/components/NavBar.vue'
import HomeCard from '@/components/HomeCard.vue'
import UserAvatar from '@/assets/images/avatar.png'
import GoodsCard from '../components/GoodsCard.vue'
import OrderCard from '../components/OrderCard.vue'
import EmptyCard from '@/components/EmptyCard.vue'
import NoData from '@/components/NoData.vue'
import TipsDialog from '@/components/TipsDialog.vue'
import { MallService } from '@/logics/services/mall'
import type { PageListData } from '@/types'
import { ofuscateMobile, simpleCopy } from '@/utils/utils'
import type { APIGetGoodsReqData, APIGetOrderReqData } from '@/types/api/mall'
import { UserService } from '@/logics/services/user'
import { useRouter } from 'vue-router'
import { TabType } from '@/helpers/constants/mall'
import { AppService } from '@/logics/services/app'
let observer: IntersectionObserver | null = null
const appService = new AppService()
const mallService = new MallService()
const userService = new UserService()
const tipsDialogRef = ref<InstanceType<typeof TipsDialog>>()
const router = useRouter()
const mobile = ref<string>('')
const userName = computed(() => {
  if (mobile.value) {
    return `会员用户${ofuscateMobile(mobile.value)}`
  }
  return '会员用户'
})
const emptyData = { page: 1, size: 10, loading: false, loadAll: false, list: [] }
const observerRef = ref<HTMLElement | null>(null)
// 当前tab
const curTab = ref(TabType.Goods)
// 用户信息
const userData = ref({
  avatar: UserAvatar,
  username: '',
  gwj: '',
})
// 商品列表
const goodsData = ref<PageListData<GoodsItem>>({
  page: 1,
  size: 10,
  loading: false,
  loadAll: false,
  list: [],
})
// 订单列表
const orderData = ref<PageListData<OrderItem>>({
  page: 1,
  size: 10,
  loading: false,
  loadAll: false,
  list: [],
})
// 查询用户信息
const queryUserInfo = async () => {
  const user = await appService.getAPPUserInfo()
  mobile.value = user.mobile
  userData.value.avatar = user.avatar || UserAvatar
  if (!mobile.value) {
    return
  }
  const info = await userService.getUserInfo({
    mobile: mobile.value,
  })
  userData.value.gwj = info.gwj
}
// 查询列表
const queryList = () => {
  switch (curTab.value) {
    case TabType.Goods:
      queryGoods()
      break
    case TabType.Order:
      queryOrder()
      break
    default:
      break
  }
}
// 加载更多
const loadoreList = () => {
  switch (curTab.value) {
    case TabType.Goods:
      goodsData.value.page++
      queryGoods()
      break
    case TabType.Order:
      orderData.value.page++
      queryOrder()
      break
    default:
      break
  }
}
// 重置列表
const resetList = () => {
  goodsData.value = simpleCopy(emptyData)
  orderData.value = simpleCopy(emptyData)
}
// 获取商品列表
const queryGoods = async () => {
  try {
    const { page, size, loading, loadAll } = goodsData.value

    if (loading || loadAll) {
      return
    }
    goodsData.value.loading = true
    const params: APIGetGoodsReqData = {
      page,
      page_size: size,
      q: '',
    }
    const list = await mallService.getGoodsList(params)
    goodsData.value.loading = false
    goodsData.value.loadAll = list.length < size
    goodsData.value.list = page === 1 ? list : [...goodsData.value.list, ...list]
  } catch (err: unknown) {
    goodsData.value.loading = false
    console.error('获取商品列表失败', err)
  }
}
// 获取订单列表
const queryOrder = async () => {
  try {
    const { page, size, loading, loadAll } = orderData.value
    if (loading || loadAll) {
      return
    }
    orderData.value.loading = true
    const params: APIGetOrderReqData = {
      page,
      size,
    }
    const { list = [] } = await mallService.getOrderList(params)
    orderData.value.loading = false
    orderData.value.loadAll = list.length < size
    orderData.value.list = page === 1 ? list : [...orderData.value.list, ...list]
  } catch (err: unknown) {
    orderData.value.loading = false
    console.error('获取订单列表失败', err)
  }
}
// 点击商品
const handleClickGoods = (goods: GoodsItem) => {
  router.push({
    name: 'goodsDetail',
    query: {
      goodsId: goods.goodsId,
      mobile: mobile.value,
      goods: JSON.stringify(goods),
    },
  })
}
// 查看记录
const handleRecord = () => {
  router.push({ name: 'recordDetail' })
}
const handleTips = () => {
  tipsDialogRef.value?.openDialog()
}
// 点击订单 todo
const handleClickOrder = () => {}
// 切换用户
const handleChangeUser = async () => {
  await appService.openAppLoginPage()
  queryUserInfo()
}
const handleBack = () => {
  // browserBack()
  appService.closeAppPage()
}
const handleRefresh = () => {
  window.location.reload()
}
const setUp = () => {
  resetList()
  listenObserver()
  queryUserInfo()
  queryList()
}
const setDown = () => {
  offObserver()
}
const listenObserver = () => {
  offObserver()
  observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      loadoreList()
    }
  })
  observer.observe(observerRef.value as HTMLElement)
}
const offObserver = () => {
  if (observer) {
    observer.disconnect()
  }
}
onMounted(() => {
  setUp()
})

onBeforeUnmount(() => {
  setDown()
})
</script>
<style lang="scss" scoped>
.page {
  width: 100%;
  min-width: 375px;
  min-height: 100vh;
  box-sizing: border-box;
  background: #fff;
  padding: 0 0 24px 0;
}
// 商品
.goods {
  padding: 16px 12px;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  .goods-item {
    width: 50%;
    margin-bottom: 6px;
  }
  .goods-item:nth-child(odd) {
    padding-right: 11px;
  }
}
// 订单
.order {
  .order-item {
    margin-top: 13px;
  }
}
// 记录
.record {
  .record-item {
    margin-top: 17px;
  }
}
.observer {
  width: 100%;
  height: 1px;
  background: transparent;
}
</style>
